<template>
  <div class="console-enhanced">
    <NavBar />
    
    <!-- 控制台头部 -->
    <div class="console-header">
      <div class="header-left">
        <h1>应用管理控制台</h1>
        <p>管理您的应用，查看数据统计，获取技术支持</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="createApp" icon="el-icon-plus">
          创建新应用
        </el-button>
        <el-button @click="refreshData" icon="el-icon-refresh">
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-overview">
      <div class="stat-card" v-for="(stat, index) in overviewStats" :key="index">
        <div class="stat-icon">{{ stat.icon }}</div>
        <div class="stat-content">
          <div class="stat-number">{{ stat.number }}</div>
          <div class="stat-label">{{ stat.label }}</div>
          <div class="stat-trend" :class="stat.trend > 0 ? 'up' : 'down'">
            <i :class="stat.trend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
            {{ Math.abs(stat.trend) }}%
          </div>
        </div>
      </div>
    </div>

    <!-- 数据可视化仪表板 -->
    <div class="dashboard-section">
      <div class="dashboard-header">
        <h2>数据可视化仪表板</h2>
        <div class="dashboard-controls">
          <el-select v-model="selectedTimeRange" size="small" @change="updateDashboard">
            <el-option label="最近7天" :value="7" />
            <el-option label="最近30天" :value="30" />
            <el-option label="最近90天" :value="90" />
          </el-select>
          <el-button-group size="small">
            <el-button @click="refreshDashboard" icon="el-icon-refresh">刷新</el-button>
            <el-button @click="exportDashboardData" icon="el-icon-download">导出数据</el-button>
          </el-button-group>
        </div>
      </div>
      
      <div class="charts-grid">
        <!-- SDK请求趋势图 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>SDK请求趋势</h3>
            <div class="chart-actions">
              <el-radio-group v-model="chartType" size="mini" @change="updateChartType">
                <el-radio-button label="line">折线图</el-radio-button>
                <el-radio-button label="bar">柱状图</el-radio-button>
              </el-radio-group>
              <el-button-group size="mini">
                <el-button icon="el-icon-refresh" @click="resetChartZoom('sdk-trends')">重置</el-button>
                <el-button icon="el-icon-download" @click="exportChart('sdk-trends')">导出</el-button>
              </el-button-group>
            </div>
          </div>
          <div class="chart-container">
            <canvas id="sdk-trends-chart"></canvas>
          </div>
        </div>

        <!-- 平台分布饼图 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>平台分布</h3>
            <div class="chart-actions">
              <el-select v-model="platformMetric" size="mini" @change="updatePlatformChart">
                <el-option label="请求数" value="requests" />
                <el-option label="用户数" value="users" />
                <el-option label="成功率" value="success_rate" />
              </el-select>
              <el-button-group size="mini">
                <el-button icon="el-icon-refresh" @click="resetChartZoom('platform')">重置</el-button>
                <el-button icon="el-icon-download" @click="exportChart('platform')">导出</el-button>
              </el-button-group>
            </div>
          </div>
          <div class="chart-container">
            <canvas id="platform-chart"></canvas>
          </div>
        </div>

        <!-- 性能指标仪表盘 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>性能指标</h3>
            <el-tag size="mini" :type="performanceStatus.type">{{ performanceStatus.text }}</el-tag>
          </div>
          <div class="performance-metrics">
            <div class="metric-item" v-for="(metric, index) in performanceMetrics" :key="index">
              <div class="metric-label">{{ metric.label }}</div>
              <div class="metric-value">{{ metric.value }}</div>
              <div class="metric-bar">
                <div class="metric-bar-fill" :style="{ width: metric.percentage + '%', backgroundColor: metric.color }"></div>
              </div>
              <div class="metric-percentage">{{ metric.percentage }}%</div>
            </div>
          </div>
        </div>

        <!-- 错误率趋势图 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>错误率分析</h3>
            <div class="chart-actions">
              <el-select v-model="errorType" size="mini" @change="updateErrorChart">
                <el-option label="总错误率" value="total" />
                <el-option label="API错误" value="api" />
                <el-option label="网络错误" value="network" />
              </el-select>
              <el-button-group size="mini">
                <el-button icon="el-icon-refresh" @click="resetChartZoom('error')">重置</el-button>
                <el-button icon="el-icon-download" @click="exportChart('error')">导出</el-button>
              </el-button-group>
            </div>
          </div>
          <div class="chart-container">
            <canvas id="error-chart"></canvas>
          </div>
        </div>
      </div>

      <!-- 实时数据面板 -->
      <div class="realtime-panel">
        <div class="realtime-header">
          <h3>实时监控</h3>
          <div class="realtime-status">
            <span class="status-indicator" :class="{ active: isRealtimeActive }"></span>
            {{ isRealtimeActive ? '监控中' : '已暂停' }}
          </div>
        </div>
        <div class="realtime-metrics">
          <div class="realtime-metric" v-for="(metric, index) in realtimeMetrics" :key="index">
            <div class="metric-icon">{{ metric.icon }}</div>
            <div class="metric-content">
              <div class="metric-label">{{ metric.label }}</div>
              <div class="metric-value">{{ metric.value }}</div>
              <div class="metric-change" :class="metric.change > 0 ? 'positive' : 'negative'">
                {{ metric.change > 0 ? '+' : '' }}{{ metric.change }}%
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 应用列表 -->
    <div class="apps-section">
      <div class="section-header">
        <h2>我的应用</h2>
        <div class="section-actions">
          <el-input
            v-model="searchQuery"
            placeholder="搜索应用..."
            prefix-icon="el-icon-search"
            style="width: 250px"
            @input="handleSearch"
          />
          <el-select v-model="filterStatus" placeholder="状态筛选" style="width: 120px">
            <el-option label="全部状态" value="" />
            <el-option label="运行中" value="active" />
            <el-option label="已暂停" value="paused" />
            <el-option label="已过期" value="expired" />
          </el-select>
        </div>
      </div>

      <div class="apps-grid">
        <div class="app-card" v-for="(app, index) in filteredApps" :key="index">
          <div class="app-header">
            <div class="app-icon">
              <img :src="app.icon || defaultIcon" alt="app icon" />
            </div>
            <div class="app-info">
              <h3>{{ app.name }}</h3>
              <p>{{ app.description || '暂无描述' }}</p>
              <div class="app-status" :class="getStatusClass(app.status)">
                {{ getStatusText(app.status) }}
              </div>
            </div>
            <div class="app-actions">
              <el-dropdown @command="handleAppAction($event, app)">
                <el-button type="text" icon="el-icon-more"></el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="view" icon="el-icon-view">
                    查看详情
                  </el-dropdown-item>
                  <el-dropdown-item command="stats" icon="el-icon-data-line">
                    数据统计
                  </el-dropdown-item>
                  <el-dropdown-item command="config" icon="el-icon-setting">
                    应用配置
                  </el-dropdown-item>
                  <el-dropdown-item command="api" icon="el-icon-key">
                    API密钥
                  </el-dropdown-item>
                  <el-dropdown-item command="test" icon="el-icon-video-play">
                    开发测试
                  </el-dropdown-item>
                  <el-dropdown-item command="edit" icon="el-icon-edit">
                    编辑信息
                  </el-dropdown-item>
                  <el-dropdown-item 
                    :command="app.status === 'active' ? 'pause' : 'resume'" 
                    :icon="app.status === 'active' ? 'el-icon-video-pause' : 'el-icon-video-play'"
                    divided
                  >
                    {{ app.status === 'active' ? '暂停服务' : '恢复服务' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" icon="el-icon-delete" style="color: #f56c6c;">
                    删除应用
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>

          <div class="app-stats">
            <div class="stat-item">
              <div class="stat-label">今日安装</div>
              <div class="stat-value">{{ app.todayInstalls || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">本周安装</div>
              <div class="stat-value">{{ app.weekInstalls || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">总安装数</div>
              <div class="stat-value">{{ app.totalInstalls || 0 }}</div>
            </div>
          </div>

          <div class="app-footer">
            <div class="app-meta">
              <span>创建于: {{ formatDate(app.created_at) }}</span>
              <span>APP Key: {{ app.appkey }}</span>
            </div>
            <div class="app-actions-bottom">
              <el-button size="small" @click="viewAppDetail(app)">查看详情</el-button>
              <el-button size="small" type="primary" @click="viewAppStats(app)">数据统计</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredApps.length === 0" class="empty-state">
        <div class="empty-icon">📱</div>
        <h3>暂无应用</h3>
        <p>创建您的第一个应用，开始免邀请码安装归因之旅</p>
        <el-button type="primary" @click="createApp">创建应用</el-button>
      </div>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
      <h3>快速操作</h3>
      <div class="action-grid">
        <div class="action-item" @click="gotoDocs">
          <div class="action-icon">📚</div>
          <div class="action-content">
            <h4>开发文档</h4>
            <p>查看SDK集成文档</p>
          </div>
        </div>
        <div class="action-item" @click="gotoPricing">
          <div class="action-icon">💰</div>
          <div class="action-content">
            <h4>服务价格</h4>
            <p>了解定价方案</p>
          </div>
        </div>
        <div class="action-item" @click="gotoSupport">
          <div class="action-icon">🎧</div>
          <div class="action-content">
            <h4>技术支持</h4>
            <p>获取专业帮助</p>
          </div>
        </div>
        <div class="action-item" @click="gotoTest">
          <div class="action-icon">🧪</div>
          <div class="action-content">
            <h4>在线测试</h4>
            <p>测试归因功能</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 最近活动 -->
    <div class="recent-activity">
      <h3>最近活动</h3>
      <div class="activity-list">
        <div class="activity-item" v-for="(activity, index) in recentActivities" :key="index">
          <div class="activity-icon">{{ activity.icon }}</div>
          <div class="activity-content">
            <div class="activity-title">{{ activity.title }}</div>
            <div class="activity-time">{{ activity.time }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { appsListApi, getAppKeyApi, getSDKStatsApi } from '@/api/apps';
import NavBar from '@/components/NavBarEnhanced.vue';
import { Chart, registerables } from 'chart.js';

Chart.register(...registerables);

export default {
  components: {
    NavBar
  },
  data() {
    return {
      apps: [],
      searchQuery: '',
      filterStatus: '',
      overviewStats: [
        {
          icon: '📱',
          number: '0',
          label: '总应用数',
          trend: 12
        },
        {
          icon: '📈',
          number: '0',
          label: '今日安装',
          trend: 8
        },
        {
          icon: '🎯',
          number: '0',
          label: '本周安装',
          trend: -3
        },
        {
          icon: '👥',
          number: '0',
          label: '总安装数',
          trend: 15
        }
      ],
      recentActivities: [
        {
          icon: '🚀',
          title: '新应用 "电商APP" 创建成功',
          time: '2小时前'
        },
        {
          icon: '📊',
          title: '应用 "社交APP" 安装量突破1000',
          time: '1天前'
        },
        {
          icon: '🔧',
          title: 'API密钥已更新',
          time: '2天前'
        }
      ],
      defaultIcon: 'https://via.placeholder.com/80x80/667eea/ffffff?text=APP',
      
      // 仪表板数据
      selectedTimeRange: 30,
      chartType: 'line',
      platformMetric: 'requests',
      errorType: 'total',
      isRealtimeActive: true,
      
      // 图表实例
      sdkTrendsChart: null,
      platformChart: null,
      errorChart: null,
      
      // 性能指标
      performanceMetrics: [
        { label: '平均响应时间', value: '120ms', percentage: 85, color: '#67C23A' },
        { label: '成功率', value: '98.5%', percentage: 98, color: '#409EFF' },
        { label: '错误率', value: '1.5%', percentage: 15, color: '#F56C6C' },
        { label: '并发处理', value: '良好', percentage: 78, color: '#E6A23C' }
      ],
      
      // 实时监控数据
      realtimeMetrics: [
        { icon: '⚡', label: '实时请求', value: '1,234', change: 5.2 },
        { icon: '🔥', label: '活跃用户', value: '892', change: -2.1 },
        { icon: '⚠️', label: '错误告警', value: '3', change: -15.3 },
        { icon: '📊', label: '数据吞吐', value: '2.1MB/s', change: 8.7 }
      ],
      
      realtimeTimer: null,
      
      // 数据缓存
      dataCache: new Map(),
      cacheTimeout: 5 * 60 * 1000, // 5分钟缓存
      
      // 图表导出配置
      chartExportOptions: {
        width: 1200,
        height: 600,
        backgroundColor: '#ffffff'
      }
    };
  },
  computed: {
    filteredApps() {
      let filtered = this.apps;
      
      // 搜索过滤
      if (this.searchQuery) {
        filtered = filtered.filter(app => 
          app.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
          app.appkey.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      }
      
      // 状态过滤
      if (this.filterStatus) {
        filtered = filtered.filter(app => app.status === this.filterStatus);
      }
      
      return filtered;
    },
    
    performanceStatus() {
      const avgPercentage = this.performanceMetrics.reduce((sum, metric) => sum + metric.percentage, 0) / this.performanceMetrics.length;
      if (avgPercentage >= 90) return { type: 'success', text: '优秀' };
      if (avgPercentage >= 80) return { type: 'info', text: '良好' };
      if (avgPercentage >= 70) return { type: 'warning', text: '一般' };
      return { type: 'danger', text: '需优化' };
    }
  },
  methods: {
    createApp() {
      this.$router.push('/console/create');
    },
    
    viewAppDetail(app) {
      this.$router.push({ path: '/console/detail', query: { id: app.id } });
    },
    
    viewAppStats(app) {
      this.$router.push({ path: '/console/stats', query: { id: app.id } });
    },
    
    editApp(app) {
      this.$router.push({ path: '/console/update', query: { id: app.id } });
    },
    
    handleAppAction(command, app) {
      switch (command) {
        case 'view':
          this.viewAppDetail(app);
          break;
        case 'stats':
          this.viewAppStats(app);
          break;
        case 'config':
          this.editApp(app);
          break;
        case 'api':
          this.showApiKey(app);
          break;
        case 'test':
          this.openTestTool(app);
          break;
        case 'edit':
          this.editApp(app);
          break;
        case 'pause':
          this.pauseApp(app);
          break;
        case 'resume':
          this.resumeApp(app);
          break;
        case 'delete':
          this.deleteApp(app);
          break;
      }
    },
    
    async showApiKey(app) {
      try {
        const res = await getAppKeyApi({ app_id: app.id });
        if (res.code === 200) {
          this.$alert(`
            <div style="text-align: left;">
              <p><strong>APP Key:</strong> ${res.data.appkey}</p>
              <p><strong>API Secret:</strong> ${res.data.secret}</p>
              <p style="color: #f56c6c; margin-top: 10px;">
                ⚠️ 请妥善保管您的API密钥，不要泄露给他人
              </p>
            </div>
          `, 'API密钥', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '复制密钥',
            callback: action => {
              if (action === 'confirm') {
                this.copyToClipboard(`${res.data.appkey}:${res.data.secret}`);
              }
            }
          });
        }
      } catch (error) {
        this.$message.error('获取API密钥失败');
      }
    },
    
    openTestTool(app) {
      const testUrl = `/console/test?app_id=${app.id}&appkey=${app.appkey}`;
      window.open(testUrl, '_blank');
    },
    
    pauseApp(app) {
      this.$confirm('确定要暂停该应用的服务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用暂停API
        this.$message.success('应用已暂停');
      });
    },
    
    resumeApp(app) {
      this.$confirm('确定要恢复该应用的服务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 调用恢复API
        this.$message.success('应用已恢复');
      });
    },
    
    deleteApp(app) {
      this.$confirm('此操作将永久删除该应用，是否继续？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        // 调用删除API
        this.$message.success('应用已删除');
        this.getAppsList();
      });
    },
    
    handleSearch() {
      // 搜索逻辑已在computed中实现
    },
    
    getStatusClass(status) {
      return {
        'status-active': status === 'active',
        'status-paused': status === 'paused',
        'status-expired': status === 'expired'
      };
    },
    
    getStatusText(status) {
      const statusMap = {
        'active': '运行中',
        'paused': '已暂停',
        'expired': '已过期'
      };
      return statusMap[status] || '未知';
    },
    
    formatDate(dateStr) {
      return new Date(dateStr).toLocaleDateString('zh-CN');
    },
    
    copyToClipboard(text) {
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('已复制到剪贴板');
      });
    },
    
    refreshData() {
      this.getAppsList();
      this.$message.success('数据已刷新');
    },
    
    gotoDocs() {
      this.$router.push('/docs');
    },
    
    gotoPricing() {
      this.$router.push('/price');
    },
    
    gotoSupport() {
      this.$message.info('技术支持功能开发中');
    },
    
    gotoTest() {
      this.$message.info('在线测试功能开发中');
    },
    
    async getAppsList() {
      try {
        const res = await appsListApi();
        if (res.code === 200) {
          this.apps = res.data.list || [];
          this.updateOverviewStats();
        } else {
          this.$message.error(res.msg);
        }
      } catch (error) {
        this.$message.error('获取应用列表失败');
      }
    },
    
    updateOverviewStats() {
      const totalApps = this.apps.length;
      const todayInstalls = this.apps.reduce((sum, app) => sum + (app.todayInstalls || 0), 0);
      const weekInstalls = this.apps.reduce((sum, app) => sum + (app.weekInstalls || 0), 0);
      const totalInstalls = this.apps.reduce((sum, app) => sum + (app.totalInstalls || 0), 0);
      
      this.overviewStats = [
        { icon: '📱', number: totalApps.toString(), label: '总应用数', trend: 12 },
        { icon: '📈', number: todayInstalls.toString(), label: '今日安装', trend: 8 },
        { icon: '🎯', number: weekInstalls.toString(), label: '本周安装', trend: -3 },
        { icon: '👥', number: totalInstalls.toString(), label: '总安装数', trend: 15 }
      ];
    },
    
    // 仪表板相关方法
    initDashboard() {
      this.$nextTick(() => {
        this.initCharts();
        this.loadDashboardData();
      });
    },
    
    initCharts() {
      this.initSDKTrendsChart();
      this.initPlatformChart();
      this.initErrorChart();
    },
    
    initSDKTrendsChart() {
      const ctx = document.getElementById('sdk-trends-chart');
      if (!ctx) return;
      
      this.sdkTrendsChart = new Chart(ctx, {
        type: this.chartType,
        data: {
          labels: this.generateDateLabels(7),
          datasets: [{
            label: 'SDK请求数',
            data: this.generateTrendData(7),
            borderColor: '#409EFF',
            backgroundColor: this.chartType === 'line' ? 'rgba(64, 158, 255, 0.1)' : '#409EFF',
            tension: 0.4,
            fill: this.chartType === 'line',
            pointBackgroundColor: '#409EFF',
            pointBorderColor: '#fff',
            pointBorderWidth: 2,
            pointRadius: 4,
            pointHoverRadius: 6
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          interaction: {
            intersect: false,
            mode: 'index'
          },
          plugins: {
            legend: {
              display: false
            },
            tooltip: {
              backgroundColor: 'rgba(0, 0, 0, 0.8)',
              titleColor: '#fff',
              bodyColor: '#fff',
              borderColor: '#409EFF',
              borderWidth: 1,
              cornerRadius: 4,
              displayColors: false,
              callbacks: {
                title: function(context) {
                  return `日期: ${context[0].label}`;
                },
                label: function(context) {
                  return `请求数: ${context.parsed.y.toLocaleString()}`;
                }
              }
            },
            zoom: {
              zoom: {
                wheel: {
                  enabled: true,
                },
                pinch: {
                  enabled: true
                },
                mode: 'x',
              },
              pan: {
                enabled: true,
                mode: 'x',
              }
            }
          },
          scales: {
            y: {
              beginAtZero: true,
              ticks: {
                callback: function(value) {
                  return value.toLocaleString();
                }
              }
            }
          },
          onClick: (event, elements) => {
            if (elements.length > 0) {
              const index = elements[0].index;
              const label = this.sdkTrendsChart.data.labels[index];
              const value = this.sdkTrendsChart.data.datasets[0].data[index];
              this.$message.info(`${label}: ${value.toLocaleString()} 次请求`);
            }
          }
        }
      });
    },
    
    initPlatformChart() {
      const ctx = document.getElementById('platform-chart');
      if (!ctx) return;
      
      this.platformChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
          labels: ['Android', 'iOS', 'Web', '其他'],
          datasets: [{
            data: [45, 30, 20, 5],
            backgroundColor: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: 'bottom'
            }
          }
        }
      });
    },
    
    initErrorChart() {
      const ctx = document.getElementById('error-chart');
      if (!ctx) return;
      
      this.errorChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: this.generateDateLabels(7),
          datasets: [{
            label: '错误率 (%)',
            data: [2.1, 1.8, 2.5, 1.2, 3.1, 1.9, 2.3],
            borderColor: '#F56C6C',
            backgroundColor: 'rgba(245, 108, 108, 0.1)',
            tension: 0.4,
            fill: true
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false
            }
          },
          scales: {
            y: {
              beginAtZero: true,
              max: 5
            }
          }
        }
      });
    },
    
    generateDateLabels(days) {
      const labels = [];
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        labels.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }));
      }
      return labels;
    },
    
    generateTrendData(days) {
      const data = [];
      for (let i = 0; i < days; i++) {
        data.push(Math.floor(Math.random() * 1000) + 500);
      }
      return data;
    },
    
    loadDashboardData() {
      // 加载仪表板数据
      if (this.apps.length > 0) {
        this.loadSDKStats();
      }
    },
    
    async loadSDKStats() {
      try {
        // 获取第一个应用的SDK统计数据作为示例
        const firstApp = this.apps[0];
        if (firstApp && firstApp.appkey) {
          const response = await getSDKStatsApi(firstApp.appkey, this.selectedTimeRange);
          if (response.code === 200) {
            this.updateChartsWithData(response.data);
          }
        }
      } catch (error) {
        console.error('加载SDK统计数据失败:', error);
      }
    },
    
    updateChartsWithData(data) {
      // 使用真实数据更新图表
      if (this.sdkTrendsChart && data.usage) {
        const trendData = this.processTrendData(data.usage);
        this.sdkTrendsChart.data.datasets[0].data = trendData;
        this.sdkTrendsChart.update();
      }
    },
    
    processTrendData(usageData) {
      // 处理使用数据生成趋势数据
      return usageData.slice(0, 7).map(item => item.count || 0);
    },
    
    updateDashboard() {
      this.loadDashboardData();
    },
    
    refreshDashboard() {
      this.loadDashboardData();
      this.$message.success('仪表板已刷新');
    },
    
    updateChartType() {
      if (this.sdkTrendsChart) {
        this.sdkTrendsChart.destroy();
      }
      this.initSDKTrendsChart();
    },
    
    updatePlatformChart() {
      this.$message.info('平台分布图表已更新');
    },
    
    updateErrorChart() {
      this.$message.info('错误率图表已更新');
    },
    
    startRealtimeMonitoring() {
      this.realtimeTimer = setInterval(() => {
        if (this.isRealtimeActive) {
          this.updateRealtimeMetrics();
        }
      }, 10000); // 每10秒更新一次
    },
    
    stopRealtimeMonitoring() {
      if (this.realtimeTimer) {
        clearInterval(this.realtimeTimer);
      }
    },
    
    updateRealtimeMetrics() {
      this.realtimeMetrics.forEach(metric => {
        const change = (Math.random() - 0.5) * 10;
        metric.change = parseFloat(change.toFixed(1));
      });
    },
    
    destroyCharts() {
      if (this.sdkTrendsChart) {
        this.sdkTrendsChart.destroy();
      }
      if (this.platformChart) {
        this.platformChart.destroy();
      }
      if (this.errorChart) {
        this.errorChart.destroy();
      }
    },
    
    // 数据缓存相关方法
    getCacheKey(type, params = {}) {
      return `${type}-${JSON.stringify(params)}`;
    },
    
    setCache(key, data) {
      this.dataCache.set(key, {
        data: data,
        timestamp: Date.now()
      });
    },
    
    getCache(key) {
      const cached = this.dataCache.get(key);
      if (cached && (Date.now() - cached.timestamp) < this.cacheTimeout) {
        return cached.data;
      }
      return null;
    },
    
    clearExpiredCache() {
      const now = Date.now();
      for (const [key, value] of this.dataCache.entries()) {
        if (now - value.timestamp > this.cacheTimeout) {
          this.dataCache.delete(key);
        }
      }
    },
    
    // 图表导出功能
    async exportChart(chartType) {
      try {
        let chart;
        let filename;
        
        switch (chartType) {
          case 'sdk-trends':
            chart = this.sdkTrendsChart;
            filename = `SDK趋势图-${new Date().toISOString().split('T')[0]}.png`;
            break;
          case 'platform':
            chart = this.platformChart;
            filename = `平台分布图-${new Date().toISOString().split('T')[0]}.png`;
            break;
          case 'error':
            chart = this.errorChart;
            filename = `错误率分析图-${new Date().toISOString().split('T')[0]}.png`;
            break;
          default:
            this.$message.warning('不支持的图表类型');
            return;
        }
        
        if (!chart) {
          this.$message.warning('图表尚未加载完成');
          return;
        }
        
        // 获取图表的canvas元素
        const canvas = chart.canvas;
        
        // 创建新的canvas用于导出（添加背景色）
        const exportCanvas = document.createElement('canvas');
        const exportCtx = exportCanvas.getContext('2d');
        
        exportCanvas.width = this.chartExportOptions.width;
        exportCanvas.height = this.chartExportOptions.height;
        
        // 填充背景色
        exportCtx.fillStyle = this.chartExportOptions.backgroundColor;
        exportCtx.fillRect(0, 0, exportCanvas.width, exportCanvas.height);
        
        // 绘制图表
        exportCtx.drawImage(canvas, 0, 0, exportCanvas.width, exportCanvas.height);
        
        // 转换为blob并下载
        exportCanvas.toBlob((blob) => {
          if (blob) {
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            
            this.$message.success('图表导出成功！');
          } else {
            this.$message.error('图表导出失败');
          }
        }, 'image/png');
        
      } catch (error) {
        console.error('导出图表失败:', error);
        this.$message.error('图表导出失败，请重试');
      }
    },
    
    // 导出仪表板数据
    async exportDashboardData() {
      try {
        this.$message.info('正在准备导出数据...');
        
        // 准备导出数据
        const exportData = {
          dashboardInfo: {
            exportTime: new Date().toLocaleString('zh-CN'),
            timeRange: `${this.selectedTimeRange}天`,
            totalApps: this.apps.length
          },
          overviewStats: this.overviewStats,
          performanceMetrics: this.performanceMetrics,
          realtimeMetrics: this.realtimeMetrics,
          apps: this.filteredApps,
          charts: {
            sdkTrends: this.sdkTrendsChart ? this.sdkTrendsChart.data : null,
            platform: this.platformChart ? this.platformChart.data : null,
            error: this.errorChart ? this.errorChart.data : null
          }
        };
        
        // 生成JSON文件
        const dataStr = JSON.stringify(exportData, null, 2);
        const dataBlob = new Blob([dataStr], { type: 'application/json' });
        const url = URL.createObjectURL(dataBlob);
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = url;
        link.download = `xapptool-dashboard-${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 释放URL对象
        URL.revokeObjectURL(url);
        
        this.$message.success('仪表板数据导出成功！');
      } catch (error) {
        console.error('导出仪表板数据失败:', error);
        this.$message.error('数据导出失败，请重试');
      }
    },
    
    // 重置图表缩放
    resetChartZoom(chartType) {
      let chart;
      switch (chartType) {
        case 'sdk-trends':
          chart = this.sdkTrendsChart;
          break;
        case 'platform':
          chart = this.platformChart;
          break;
        case 'error':
          chart = this.errorChart;
          break;
      }
      
      if (chart) {
        chart.resetZoom();
        this.$message.info(`${chartType}图表缩放已重置`);
      }
    }
  },
  created() {
    this.getAppsList();
  },
  
  mounted() {
    this.initDashboard();
    this.startRealtimeMonitoring();
  },
  
  beforeDestroy() {
    this.stopRealtimeMonitoring();
    this.destroyCharts();
  },
};
</script>

<style scoped>
.console-enhanced {
  padding: 0;
  background: #f5f7fa;
  min-height: 100vh;
}

.site-footer {
  background: #ffffff;
  border-top: 1px solid #e4e7ed;
  padding: 1rem 2rem;
}

.footer-content {
  text-align: center;
  color: #909399;
  font-size: 0.9rem;
}

/* 控制台头部 */
.console-header {
  background: white;
  padding: 2rem;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h1 {
  margin: 0;
  color: #303133;
  font-size: 1.8rem;
}

.header-left p {
  margin: 0.5rem 0 0 0;
  color: #909399;
}

.header-right {
  display: flex;
  gap: 1rem;
}

/* 统计概览 */
.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1.5rem;
  padding: 2rem;
}

.stat-card {
  background: white;
  padding: 1.5rem;
  border-radius: 0.5rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 1rem;
}

.stat-icon {
  font-size: 2rem;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f2f5;
  border-radius: 50%;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 1.8rem;
  font-weight: bold;
  color: #303133;
  margin-bottom: 0.2rem;
}

.stat-label {
  color: #909399;
  font-size: 0.9rem;
  margin-bottom: 0.3rem;
}

.stat-trend {
  font-size: 0.8rem;
  display: flex;
  align-items: center;
  gap: 0.2rem;
}

.stat-trend.up {
  color: #67c23a;
}

.stat-trend.down {
  color: #f56c6c;
}

/* 应用列表 */
.apps-section {
  padding: 0 2rem 2rem;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.section-header h2 {
  margin: 0;
  color: #303133;
}

.section-actions {
  display: flex;
  gap: 1rem;
}

.apps-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
}

.app-card {
  background: white;
  border-radius: 0.5rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.app-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.app-header {
  padding: 1.5rem;
  display: flex;
  align-items: flex-start;
  gap: 1rem;
}

.app-icon {
  width: 60px;
  height: 60px;
  border-radius: 0.5rem;
  overflow: hidden;
  flex-shrink: 0;
}

.app-icon img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.app-info {
  flex: 1;
}

.app-info h3 {
  margin: 0 0 0.5rem 0;
  color: #303133;
}

.app-info p {
  margin: 0 0 0.5rem 0;
  color: #909399;
  font-size: 0.9rem;
}

.app-status {
  display: inline-block;
  padding: 0.2rem 0.8rem;
  border-radius: 1rem;
  font-size: 0.8rem;
  font-weight: 500;
}

.status-active {
  background: #f0f9ff;
  color: #67c23a;
}

.status-paused {
  background: #fef0f0;
  color: #f56c6c;
}

.status-expired {
  background: #fdf6ec;
  color: #e6a23c;
}

.app-actions {
  flex-shrink: 0;
}

.app-stats {
  display: flex;
  justify-content: space-around;
  padding: 1rem 1.5rem;
  background: #f8f9fa;
  border-top: 1px solid #e4e7ed;
  border-bottom: 1px solid #e4e7ed;
}

.stat-item {
  text-align: center;
}

.stat-label {
  color: #909399;
  font-size: 0.8rem;
  margin-bottom: 0.3rem;
}

.stat-value {
  color: #303133;
  font-size: 1.2rem;
  font-weight: bold;
}

.app-footer {
  padding: 1rem 1.5rem;
}

.app-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  font-size: 0.8rem;
  color: #909399;
}

.app-actions-bottom {
  display: flex;
  gap: 0.5rem;
}

/* 快速操作 */
.quick-actions {
  padding: 0 2rem 2rem;
}

.quick-actions h3 {
  margin-bottom: 1.5rem;
  color: #303133;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
}

.action-item {
  background: white;
  padding: 1.5rem;
  border-radius: 0.5rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.action-icon {
  font-size: 2rem;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f2f5;
  border-radius: 50%;
  flex-shrink: 0;
}

.action-content h4 {
  margin: 0 0 0.3rem 0;
  color: #303133;
}

.action-content p {
  margin: 0;
  color: #909399;
  font-size: 0.9rem;
}

/* 最近活动 */
.recent-activity {
  padding: 0 2rem 2rem;
}

.recent-activity h3 {
  margin-bottom: 1.5rem;
  color: #303133;
}

.activity-list {
  background: white;
  border-radius: 0.5rem;
  overflow: hidden;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e4e7ed;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-icon {
  font-size: 1.5rem;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f2f5;
  border-radius: 50%;
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
}

.activity-title {
  color: #303133;
  margin-bottom: 0.2rem;
}

.activity-time {
  color: #909399;
  font-size: 0.8rem;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 4rem 2rem;
  background: white;
  border-radius: 0.5rem;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  opacity: 0.5;
}

.empty-state h3 {
  color: #303133;
  margin-bottom: 0.5rem;
}

.empty-state p {
  color: #909399;
  margin-bottom: 2rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .console-header {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .stats-overview {
    grid-template-columns: repeat(2, 1fr);
    padding: 1rem;
  }
  
  .apps-section,
  .quick-actions,
  .recent-activity {
    padding: 0 1rem 2rem;
  }
  
  .section-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
  
  .section-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .apps-grid {
    grid-template-columns: 1fr;
  }
  
  .action-grid {
    grid-template-columns: 1fr;
  }
  
  .app-header {
    flex-direction: column;
    text-align: center;
  }
  
  .app-meta {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .app-actions-bottom {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .stats-overview {
    grid-template-columns: 1fr;
  }
  
  .section-actions {
    flex-direction: column;
  }
  
  .section-actions .el-input,
  .section-actions .el-select {
    width: 100% !important;
  }
}

/* 图表操作按钮样式 */
.chart-actions {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}
</style>